﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using log4net;
using Matriculex.Dominio;

namespace Matriculex.UI
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
  Inherited = true, AllowMultiple = false)]
    public sealed class AutorizexAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        private readonly ILog logger = LogManager.GetLogger("LogInFile");
        private string permissao;
        private readonly string masterPage;

        public AutorizexAttribute(string permissao) : this(permissao, null)
        {
        }

        public AutorizexAttribute(string permissao, string masterPage)
        {
            this.permissao = permissao;
            this.masterPage = masterPage;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Session["usuario"] == null)
            {
                if (String.IsNullOrEmpty(masterPage))
                {
                    filterContext.Result = Erro(filterContext);
                }
            }
            else
            {
                Aluno aluno = filterContext.HttpContext.Session["usuario"] as Aluno;
                if (aluno == null || !aluno.Ativado)
                {
                    filterContext.Result = Erro(filterContext);
                }
            }
        }

        private static ActionResult Erro(ControllerContext contexto)
        {
            return Erro(contexto.HttpContext.Request.Path);
        }

        private static ActionResult Erro(string redirectUrl)
        {
            return new RedirectResult("/Login/Login?redir=" + redirectUrl);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var handled = filterContext.ExceptionHandled;
            var result = filterContext.Result;
            if (result is ViewResult)
            {
                ((ViewResult) result).MasterName = masterPage;
            }
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {

        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (filterContext.Exception == null) return;

            logger.Error(filterContext.Exception.Message);
            filterContext.ExceptionHandled = true;
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {controller = "Login", action="Index"}));
        }
    }
}
